<?php

namespace common\behavior\ReviewRequest;

use Throwable;
use common\model\TaskModel;
use common\model\EntityModel;
use common\model\VersionModel;
use common\service\ChatService;

/**
 * 发起任务审核申请 通知到群聊
 */
class TaskReviewRequestCreateNotifyInEntityChatBehavior
{
    public function run($params)
    {
        $data = $params['record']['data'];
        if (empty($data['module_id'])) {
            return;
        }
        $reviewModuleCode = module_by_id($data['module_id'])['code'];
        if ($reviewModuleCode != 'version') {
            return;
        }
        $version = model(VersionModel::class)->where(['id' => $data['link_id']])->find();
        if (empty($version)) {
            return;
        }
        $task = model(TaskModel::class)->where(['id' => $version['link_id']])->find();
        if (empty($task)) {
            return;
        }
        $entity = model(EntityModel::class)->where(['id' => $task['entity_id']])->find();
        if (empty($entity)) {
            return;
        }
        try {
            $chatService = ChatService::getInstance();
            $chat = $chatService->createEntityChat($entity);
            if (empty($chat)) {
                return;
            }
            $message['type'] = 'audit_entity_task_message';
            $message = $chatService->getEntityTaskMessageTemplate($message, request()->getUserId(), $entity, $task);
            $chatService->pushEntityTaskMessage($message, $chat);
        } catch (Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }

    }
}